package me.flyray.biz.thymeleaf.modules.goods.rest;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.github.wxiaoqi.security.common.msg.ResponseCode;
import com.github.wxiaoqi.security.common.msg.TableResultResponse;
import com.github.wxiaoqi.security.common.qr.request.QrGoodsRequestParam;
import com.github.wxiaoqi.security.common.qr.request.QrQueryGoodsParam;
import com.github.wxiaoqi.security.common.rest.BaseController;
import com.github.wxiaoqi.security.common.util.ResponseHelper;
import com.github.wxiaoqi.security.common.util.ZipHelper;
import com.google.zxing.WriterException;

import me.flyray.biz.thymeleaf.modules.goods.biz.QrGoodsInfoBiz;
import me.flyray.biz.thymeleaf.modules.goods.entity.QrGoodsInfo;


/**
 * 商品
 * @author Administrator
 *
 */
@Controller
@RequestMapping("qrGoodsInfos")
public class QrGoodsInfoController extends BaseController<QrGoodsInfoBiz, QrGoodsInfo>  {
	
	private static final Logger logger = LoggerFactory.getLogger(QrGoodsInfoController.class);

	
	/**
	 * 查询商品列表
	 * @param param
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/list", method=RequestMethod.POST)
	public TableResultResponse<QrGoodsInfo> query(@RequestBody QrQueryGoodsParam param) {
		logger.info("查询商品列表。。。{}"+param);
		return baseBiz.queryList(param);
	}
	
	
	/**
	 * 添加
	 * @param param
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/add", method=RequestMethod.POST)
	public Map<String, Object> add(@RequestBody QrGoodsRequestParam param) {
		logger.info("添加商品。。。{}"+param);
		QrGoodsInfo goodsInfo = baseBiz.addGoodsInfo(param);
		if (goodsInfo == null) {
			return ResponseHelper.success(null, null, ResponseCode.OK.getCode(), ResponseCode.OK.getMessage());
		}else {
			return ResponseHelper.success(null, null, ResponseCode.FUNCTION_EXIST.getCode(), ResponseCode.FUNCTION_EXIST.getMessage());
		}
	}
	
	/**
	 * 导入
	 * @param param
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/import", method=RequestMethod.POST)
	public Map<String, Object> importData(@RequestBody Map<String, Object> param) {
		logger.info("添加商品。。。{}"+param);
		baseBiz.importGoodsList(param);
		return ResponseHelper.success(null, null, ResponseCode.OK.getCode(), ResponseCode.OK.getMessage());
	}
	
	/**
	 * 修改
	 * @param param
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/update", method=RequestMethod.POST)
	public Map<String, Object> update(@RequestBody QrGoodsRequestParam param) {
		logger.info("修改商品。。。{}"+param);
		QrGoodsInfo goodsInfo = baseBiz.addGoodsInfo(param);
		if (goodsInfo != null) {
			return ResponseHelper.success(null, null, ResponseCode.OK.getCode(), ResponseCode.OK.getMessage());
		}else {
			return ResponseHelper.success(null, null, ResponseCode.FUNCTION_EXIST.getCode(), ResponseCode.FUNCTION_EXIST.getMessage());
		}
	}
	
	
	/**
	 * 删除
	 * @param param
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/delete", method=RequestMethod.POST)
	public Map<String, Object> delete(@RequestBody QrGoodsRequestParam param) {
		logger.info("删除商品。。。{}"+param);
		QrGoodsInfo goodsInfo = baseBiz.deleteGoodsInfo(param);
		if (goodsInfo != null) {
			return ResponseHelper.success(null, null, ResponseCode.OK.getCode(), ResponseCode.OK.getMessage());
		}else {
			return ResponseHelper.success(null, null, ResponseCode.FUNCTION_EXIST.getCode(), ResponseCode.FUNCTION_EXIST.getMessage());
		}
	}
	
	
	/**
	 * 生成二维码
	 * @param param
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/createQr", method=RequestMethod.POST)
	public Map<String, Object> createQr(@RequestBody Map<String, Object> param) {
		logger.info("生成二维码参数。。。{}"+param);
		Map<String, Object> res = new HashMap<>();
//		if (res != null) {
//			return ResponseHelper.success(res, null, ResponseCode.OK.getCode(), ResponseCode.OK.getMessage());
//		}else {
//			return ResponseHelper.success(null, null, ResponseCode.ABNORMAL_FIELDS.getCode(), ResponseCode.ABNORMAL_FIELDS.getMessage());
//		}
		return res;
	}
	
	@RequestMapping(value="/downloadZipQr", method=RequestMethod.POST)
	public void downloadZipQr(HttpServletRequest request, HttpServletResponse response) throws IOException, WriterException {
		String idString= null; 
		try {
			BufferedReader streamReader = new BufferedReader( new InputStreamReader(request.getInputStream(), "UTF-8"));
			StringBuilder responseStrBuilder = new StringBuilder();
			String inputStr;
			while ((inputStr = streamReader.readLine()) != null)
				responseStrBuilder.append(inputStr);
			
			JSONObject jsonObject = JSONObject.parseObject(responseStrBuilder.toString());
			idString =  (String)jsonObject.get("idStr");
			logger.info("下载二维码。。。。{}"+ idString);
		} catch (Exception e) {
			e.printStackTrace();
		}
		String realPath = request.getSession().getServletContext().getRealPath("/"); 
		//1 生成二维码 
		String projectName = "商品二维码"; 
		String path = realPath + projectName; 
		File file = new File(path); 
		if (!file.exists()) { 
			file.mkdirs(); 
		} 
		baseBiz.createGoodsQr(idString, path);
		
		//2 生成zip文件 
		ZipHelper.zipCompress(path, path + ".zip"); 
		//3 下载
		String zipFileName = path + ".zip"; 
		String filename = projectName + ".zip"; 
		InputStream fis = null;
		try {
			 fis = new BufferedInputStream(new FileInputStream(zipFileName));
	         byte[] buffer = new byte[fis.available()];
	         fis.read(buffer);
	         fis.close();

	         response.reset();
	         OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
	         response.setContentType("application/octet-stream");
	         response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
	         toClient.write(buffer);
	         toClient.flush();
	         toClient.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				deleteDir(new File(path));
				fis.close();
				deleteDir(new File(zipFileName));
            } catch (Exception e) {
                e.printStackTrace();
            }
		}
		
		

		
		
		
		//设置文件MIME类型 
//		response.setContentType("multipart/form-data"); 
////		response.setCharacterEncoding("UTF-8"); 
//		//设置Content-Disposition 
//		response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "utf-8")); 
//		InputStream in = new FileInputStream(zipFileName); 
//		OutputStream out = response.getOutputStream(); 
//		//写文件 
//		int b = 0;  
//        byte[] buffer = new byte[512];  
//        while (b != -1){  
//           b = in.read(buffer);
//           if(b != -1){
//        	   out.write(buffer,0,b);//4.写到输出流(out)中   
//           }
//
//        }  
//		out.flush(); 
//		//4 删除多余文件 
//		in.close();//先关闭输入流才能删除 
//		deleteDir(new File(path)); 
//		deleteDir(new File(zipFileName)); 
//		out.close();
	}
	
	private static boolean deleteDir(File dir) { 
		if (dir.isDirectory()) { 
			String[] children = dir.list(); 
			for (String s : children) { 
				boolean success = deleteDir(new File(dir, s)); 
				if (!success) { 
					return false; 
				} 
			} 
		} 
		// 目录此时为空，可以删除 
		return dir.delete(); 
	}
	
}
	
